<template>
  <view class="mxp-grid-item" :style="[newStyle, cusStyle]" :class="cusClass" @click="emits('click')">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
  import { type CSSProperties, computed, inject, onMounted, ref } from 'vue';
  import { publicStyeProps } from '../mxp-tool/utils/public-props';
  import { type GridID, type MxpGridProps, gridInjectKey, mxpGridStore } from '../mxp-tool/store/mxp-store-grid';
  defineOptions({
    name: 'mxp-grid-item',
  });

  const props = defineProps({
    /** 索引（必传入） */
    index: { type: Number, required: true },
    ...publicStyeProps,
  });
  defineSlots<{
    /** 主体内容 */
    default?: () => void;
  }>();
  const emits = defineEmits<{
    (e: 'click'): void;
  }>();
  const gridStore = mxpGridStore();
  /** 接收mxp-form组件中的所有prop字段 */
  const mxpGridIDInjectKey = ref<GridID | undefined>(undefined);
  onMounted(() => {
    /** 解决抖音初始化父子关系初始化较晚问题 */
    mxpGridIDInjectKey.value = mxpGridIDInjectKey.value ? mxpGridIDInjectKey.value : inject<GridID>(gridInjectKey);
  });
  const gridProps = computed<MxpGridProps>(() => {
    const defGridProps: MxpGridProps = { col: 3, itemWidth: '100px', itemHeight: 'square', xSpace: '0px', ySpace: '0px' };
    if (mxpGridIDInjectKey.value && gridStore.state[mxpGridIDInjectKey.value]) {
      return gridStore.state[mxpGridIDInjectKey.value]?.gridProps || defGridProps;
    } else {
      return defGridProps;
    }
  });
  const newStyle = computed(() => {
    const style: CSSProperties = { width: gridProps.value.itemWidth };
    if (gridProps.value.col < props.index + 1) {
      style.marginTop = gridProps.value.ySpace;
    }
    if (props.index % gridProps.value.col !== 0) {
      style.marginLeft = gridProps.value.xSpace;
    }
    if (gridProps.value.itemHeight === 'square') {
      style.height = gridProps.value.itemWidth;
    } else {
      style.height = gridProps.value.itemHeight;
    }
    return style;
  });
</script>

<style lang="scss" scoped>
  .mxp-grid-item {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
